package com.liuya.safe.user.controller;

import com.liuya.common.StringUtil;
import com.liuya.common.TypeParseUtil;
import com.liuya.common.Util;
import com.liuya.safe.client.pojo.UserType;
import com.liuya.safe.model.SafeRole;
import com.liuya.safe.system.role.service.RoleManagerService;
import com.liuya.safe.user.service.UserManagerService;
import com.liuya.safe.user.service.UserRoleManagerService;
import com.liuya.safe.util.AuthUtil;
import com.liuya.safe.util.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liuya.base.BaseController;
import com.liuya.common.WebUtil;
import com.liuya.safe.model.SafeUser;

/**
 * 用户管理
 * @author liuya
 * @date 20160826
 */
//@RestController
@Controller
@Api(value = "用户管理", description = "用户管理")
@RequestMapping(value = "userMng")
public class UserManagerContrller extends BaseController{

    @Autowired
    @Qualifier("userManagerService")
    UserManagerService userService;
    @Autowired
    @Qualifier("userRoleManagerService")
    UserRoleManagerService userRoleService;
    @Autowired
    @Qualifier("roleManagerService")
    RoleManagerService roleMng;

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/userList")
    public String userList(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            handler(req, rep, map);
            return "system/userList";
        } catch (Exception e){
            return "";
        }
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/userWidget")
    public String userWidget(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            handler(req, rep, map);
            return "system/userListWidget";
        } catch (Exception e){
            return "";
        }
    }

    private void handler(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        Collection coll = null;
        int totalNumber = 0;
        // display from
        int first = WebUtil.getIntParameter(req, "first", 0);
        // display max size
        int size = WebUtil.getIntParameter(req, "size", Constants.DEFAULT_SHOW_ENTITY_SIZE);
        // search key
        String searchName = req.getParameter("name");
////        if (searchName != null) {
////            searchName = new String(searchName.getBytes("ISO-8859-1"), "UTF-8");
////        }
////        if (InitController.isSecured()) {
////            SafeUser user = SafeWebClient.getCurrentUser(req);
////
////            EntitleManagerService entitleMng = Factory.getEntitleManager("");
////            com.liuya.db.sql.Query query = entitleMng.getQuery(SafePrivilege.ASSIGN_ROLE_TO_USER_ID, user, null).getSqlQuery();
////            coll = userService.selectUsersByCustomizedJavaBean(user, null, searchName, query, first, size);
////            totalNumber = userService.selectUserCounts(user, null, searchName, query);
////        } else {
//            coll = userService.selectUsers(null, null, searchName, null, first, size);
//            totalNumber = userService.selectUserCounts(null, null, searchName, null);
////        }

        UserType userType = AuthUtil.getUserType(req);
//        String[] showUserFields = userType.getUserMetadata().getShowUserFields();
//        String[] showUserFieldDisplayNames = userType.getUserMetadata().getShowUserFieldDisplayNames();
//        String[] showUserFields = {"name", "companyName"};
//        String[] showUserFieldDisplayNames = {"Name", "Company"};
        String[] showUserFields = {"name", "account"};
        String[] showUserFieldDisplayNames = {"Name", "Account"};

        map.addAttribute("totalNumber", totalNumber);
        map.addAttribute("users", coll);
        map.addAttribute("first", first);
        map.addAttribute("size", size);
        map.addAttribute("name", searchName);
        map.addAttribute("showUserFields", showUserFields);
        map.addAttribute("showUserFieldDisplayNames", showUserFieldDisplayNames);
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/userRole")
    public String userRole(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            String strUserId = req.getParameter("userId");
            SafeUser user = userService.selectById(strUserId);
            Collection assignedRoles = userRoleService.getRoles(strUserId);

            Set assignedRoleIds = new HashSet();
            for (Iterator iter = assignedRoles.iterator(); iter.hasNext();) {
                SafeRole role = (SafeRole) iter.next();
                assignedRoleIds.add(new Integer(role.getId()));
            }

            // search key
            String searchName = req.getParameter("name");
            if (searchName != null) {
                searchName = new String(searchName.getBytes("ISO-8859-1"), "UTF-8");
            }

            Collection roles = null;
            if (StringUtil.isEmpty(searchName)) {
                roles = roleMng.getAllRoles();
            } else {
                roles = roleMng.getLikelyRoles(searchName);
            }

            req.setAttribute("roles", roles);
            req.setAttribute("assignedRoleIds", assignedRoleIds);
            req.setAttribute("user", user);

            return "system/userRoles";
        } catch (Exception e){
            return "";
        }
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/assignRoleIds")
    @ResponseBody
    public String assignRoleIds(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            String strUserId = req.getParameter("userId");
            String[] assignRoleIds = req.getParameterValues("roleId");
            Collection roleIds = TypeParseUtil.convert2Collection(assignRoleIds);
            userRoleService.assignRoles(strUserId, roleIds);
            return "";
        } catch (Exception e){
            return "";
        }
    }
}
